﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using AzureTracer.Model;
using AzureTracer.ViewModels;
using Microsoft.Phone.Controls;

namespace AzureTracer.Services
{
    public class NavigationService : INavigationService
    {
        public NavigationService() {}        

        const string DETAIL_URL = @"/Views/DetailPage.xaml";
        const string CONFIGURATION_URL = @"/Views/SettingsPage.xaml";
        const string LOGIN_URL = @"/Views/LoginPage.xaml";

        private void Navigate(string uri)
        {
            Navigate(uri, null);
        }

        private void Navigate(string uri, System.Collections.Generic.IDictionary<string, string> parameters)
        {
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame == null)
                return;

            StringBuilder uriBuilder = new StringBuilder();
            uriBuilder.Append(uri);
            if (parameters != null && parameters.Count != 0)
            {
                uriBuilder.Append("?");
                bool prependAmp = false;
                foreach (KeyValuePair<string, string> parameterPair in parameters)
                {
                    if (prependAmp)
                        uriBuilder.Append("&");
                    uriBuilder.AppendFormat("{0}={1}", parameterPair.Key, parameterPair.Value);
                    prependAmp = true;
                }
            }
            frame.Navigate(new Uri(uriBuilder.ToString(), UriKind.RelativeOrAbsolute));
        }

        public void ToDetail(LogEntity logItem)
        {
            ViewModelLocator.Detail.Log = logItem;
            Navigate(DETAIL_URL);
        }


        public void Back()
        {
            PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame == null || !frame.CanGoBack || frame.BackStack == null || frame.BackStack.Count() == 0) return;

            frame.GoBack();
        }


        public void ToConfiguration()
        {
            Navigate(CONFIGURATION_URL);
        }

        public void ToLogin()
        {
            Navigate(LOGIN_URL);
        }
    }
}
